//
//  ReceiptAddressViewController.m
//  ChunLaiZhuangClient
//
//  Created by xielihui on 16/3/12.
//  Copyright © 2016年 CLZ. All rights reserved.
//

#import "ReceiptAddressViewController.h"
#import "ReceiptAdressTableViewCell.h"
#import "ReceiptAddressEditViewController.h"
#import "ApiClient+Ext.h"
#import "AddressListModel.h"
#import "AddressEmptyView.h"
@interface ReceiptAddressViewController ()<UITableViewDataSource, UITableViewDelegate>
@property(nonatomic, strong) UIView *headView;
@property(nonatomic, strong) UIView *footView;
@property(nonatomic, strong) NSMutableDictionary *offscreenCells;
@property(weak, nonatomic) IBOutlet UIButton *confirmBtn;
@property(nonatomic, strong) AddressSubModel *selectAddressModel;
@property(nonatomic, strong) AddressEmptyView *emptyView;
@end

@implementation ReceiptAddressViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.view.clipsToBounds = YES;
    self.confirmBtn.layer.cornerRadius = 24.f;
    self.receiptAddressTableView.backgroundColor = [UIColor whiteColor];
    self.receiptAddressTableView.delegate = self;
    self.receiptAddressTableView.dataSource = self;
    self.offscreenCells = [NSMutableDictionary dictionary];
    // Do any additional setup after loading the view.
}

- (AddressEmptyView *)emptyView {
    if (!_emptyView) {
        _emptyView = [[AddressEmptyView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.width)];
        __weak typeof(self) weakSelf = self;
        _emptyView.AddNewAddressBlock = ^(){
            ReceiptAddressEditViewController *editAddressVC = [[ReceiptAddressEditViewController alloc] init];
            [weakSelf.navigationController pushViewController:editAddressVC animated:YES];
        };
        [self.view addSubview:_emptyView];
        [_emptyView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view);
            make.top.equalTo(@(10));
            make.size.mas_equalTo(CGSizeMake(300, 300));
        }];
    }
    return _emptyView;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self getAddressList];
}

- (void)getAddressList {
    [ApiClient getAddressListDidFinishLoaded:^(AddressListModel *model, NSString *path) {
        if ([model.status isEqual:@(1)]) {
            NSMutableArray *addressArray = [NSMutableArray arrayWithArray:model.data.addresses];
            self.addressListArray = addressArray;
        }
    } didFailLoaded:^(NSError *error, NSString *path) {

    }];
}


- (void)setAddressListArray:(NSMutableArray *)addressListArray {
    NSMutableArray *array = [NSMutableArray array];
    if (addressListArray.count > 0) {
        [array addObjectsFromArray:addressListArray];
        AddressSubModel *model = [[AddressSubModel alloc] init];
        [array addObject:model];
        self.emptyView.hidden = YES;
    } else {
        self.emptyView.hidden = NO;
    }
    _addressListArray = array;
    [self.receiptAddressTableView reloadData];
}

- (UIView *)headView {
    if (!_headView) {
        _headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 44.f)];
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(18, 14, 80, 16)];
        label.font = [UIFont systemFontOfSize:16.f];
        label.text = @"收货地址";
        [_headView addSubview:label];
        
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(self.view.width - 44.f, 0.f, 44, 44)];
        [button setImage:[UIImage imageNamed:@"btn_shouqi"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(closePageAction:) forControlEvents:UIControlEventTouchUpInside];
        [_headView addSubview:button];
        
        UIView *spaceLine = [[UIView alloc] initWithFrame:CGRectMake(0, 43.f, self.view.width, .8f)];
        spaceLine.backgroundColor = [UIColor colorWithRGB:0xe1e1e1];
        [_headView addSubview:spaceLine];
    }
    return _headView;
}

- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.addressListArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row < self.addressListArray.count - 1) {
        return 60.f;
    } else {
        return 50.f;
    }

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row < self.addressListArray.count - 1) {
        return 60.f;
    } else {
        return 50.f;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 44.f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell;
    if (indexPath.row < self.addressListArray.count - 1) {
        static NSString *identifier = @"ReceiptAddressCell";
        cell = [tableView dequeueReusableCellWithIdentifier:
                                            identifier];
        if (!cell) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"ReceiptAdressTableViewCell" owner:nil options:nil] lastObject];
        }
        AddressSubModel *model = [self.addressListArray objectAtIndex:indexPath.row];
        [(ReceiptAdressTableViewCell *)cell updateAddressInfo:model];
        ((ReceiptAdressTableViewCell *)cell).selectAddressBlock = ^(AddressSubModel *model) {
            self.selectAddressModel = model;
            if (model.isChecked) {
                for (AddressSubModel *addressModel in self.addressListArray) {
                    if (model != addressModel) {
                        addressModel.isChecked = NO;
                    }
                }
            }
        };

    } else {
        static NSString *identifier = @"ReceiptAddressFootCell";
        cell = [tableView dequeueReusableCellWithIdentifier:
                identifier];
        if (!cell) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"ReceiptAddressFootTableViewCell" owner:nil options:nil] lastObject];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return self.headView;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return self.footView;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    AddressSubModel *model = [self.addressListArray objectAtIndex:indexPath.row];
    ReceiptAddressEditViewController *editAddressVC = [[ReceiptAddressEditViewController alloc] initWithAddressInfo:model];
    [self.navigationController pushViewController:editAddressVC animated:YES];
}

- (void)closePageAction:(id)sender {
    if (self.closePageAction) {
        self.closePageAction();
    }
}

- (IBAction)confirmAction:(id)sender {
    if (!self.selectAddressModel) {
        [[LKDHud shareHud] showtip:@"请选择一个地址"];
        return;
    }
    [ApiClient setShippingAddress:self.selectAddressModel.address_id didFinishLoaded:^(KXJson *json, NSString *path) {
        if ([[json getStringForKey:@"status"] isEqualToString:@"1"]) {
            if (self.chooseReceiptAddressBlock) {
                self.chooseReceiptAddressBlock(self.selectAddressModel);
            }
            if (self.closePageAction) {
                self.closePageAction();
            }
        }
    } didFailLoaded:^(NSError *error, NSString *path) {
        
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
